package org.jivesoftware.openfire.plugin.headline;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.session.ClientSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * 通知推送接口
 *
 * @author lyusantu@gmail.com
 */
public class HeadlineServlet extends HttpServlet {

    private static Logger log = LoggerFactory.getLogger(HeadlineServlet.class);

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // 取消权限验证，不登陆即可访问
        AuthCheckFilter.addExclude("chatlogs/HeadlineServlet");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String user = request.getParameter("user");
        String content = request.getParameter("content");
        JSONObject json = new JSONObject();
        json.put("user", user);
        json.put("content", content);

        Message message = new Message();
        message.setType(Message.Type.headline);
        message.setBody(JSON.toJSONString(json));

        JID jid = XMPPServer.getInstance().createJID(user, null);
        Collection<ClientSession> sessions = SessionManager.getInstance().getSessions(user);
        if (sessions != null && sessions.size() > 0) {
            XMPPServer.getInstance().getRoutingTable().routePacket(jid, message, true);
            log.info(jid.toBareJID() + " 在线, 成功发送通知");
        } else {
            // 用户不在线,发送离线消息
            log.info(jid.toBareJID() + " 不在线,发送离线消息");
        }

        replyMessage(JSON.toJSONString(json), response, out);
    }

    @Override
    public void destroy() {
        AuthCheckFilter.removeExclude("chatlogs/HeadlineServlet");
    }

    private void replyMessage(String message, HttpServletResponse response, PrintWriter out) {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        out.write(message);
        out.close();
    }

}
